using System;
using System.Threading;
using System.Windows.Forms;
using Widgetsphere.Core.Util;
using Widgetsphere.Core.Logging;

namespace Widgetsphere.Core.Exceptions
{
	public partial class ThreadExceptionHandler
	{
		private static readonly TraceSwitch mLogSwitch = LogClass.WSCommonUtil;

		public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
		{
			MessageLog.LogVerbose(mLogSwitch, "Call: Application_ThreadException(object sender, ThreadExceptionEventArgs e)");
			try
			{
				ShowThreadExceptionDialog(e.Exception);
			}
			catch
			{
				try
				{
					MessageBox.Show("Fatal Error", 
						"Fatal Error",
						MessageBoxButtons.OK, 
						MessageBoxIcon.Stop);
				}
				finally
				{
					Application.Exit();
				}
			}
		}

    public void Application_ThreadException(object sender, UnhandledExceptionEventArgs e)
    {
      MessageLog.LogVerbose(mLogSwitch, "Call: Application_ThreadException(object sender, UnhandledExceptionEventArgs e)");
      try
      {
        if (e.IsTerminating)
        {
          MessageLog.LogError(mLogSwitch, e.ExceptionObject.ToString());
        }
        else
        {
          ShowThreadExceptionDialog(e.ExceptionObject);
        }
      }
      catch
      {
        try
        {
          MessageBox.Show("Fatal Error",
            "Fatal Error",
            MessageBoxButtons.OK,
            MessageBoxIcon.Stop);
        }
        finally
        {
          Application.Exit();
        }
      }
    }


		private void ShowThreadExceptionDialog(object ex)
    {
      string newLine = Environment.NewLine;
      string errorMessage = String.Empty;
      if (ex.GetType().IsAssignableFrom(typeof(System.Exception))) 
      {
        Exception systemException = (Exception)ex;
        errorMessage = "Unhandled Exception: " + systemException.Message + newLine +
        "Exception Type: " + systemException.GetType() + newLine +
        "Stack Trace:" + newLine +
        systemException.StackTrace;
      }
      else
      {
        errorMessage = ex.ToString();
      }

      ThreadExceptionHandlerForm exceptionForm = new ThreadExceptionHandlerForm(errorMessage);
      if (exceptionForm.ShowDialog() == DialogResult.Abort)
      {
        Application.Exit();
      }
    }
	} 
}
